<template>
  <div class="detail-container" v-loading="loading">
     <el-card shadow="never" style="margin-top: 15px">
      <div class="operate-container">
        <i class="el-icon-warning color-danger" style="margin-left: 20px"></i>
          <span class="color-danger">当前合同状态：{{orderInfo.orderStateStr}}</span>
<!--          <el-button type="primary" @click="syncOneOrder" :loading="btnLoading5" style="float:right;margin-top:20px;margin-right:20px">同步SAP内容</el-button>-->
      </div>
       <el-form size="mini" label-width="100px" class="minRoW" :rules="rules" ref="orderForm" :model="orderInfo">
            <div style="margin-top: 20px">
              <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
              <span class="font-small">基本信息</span>
            </div>
            <el-card shadow="never" style="margin-top:20px">
                  <el-row>
                      <el-col :span="8">
                          <el-form-item label="合同编号：">{{orderInfo.orderSn}}</el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="采购日期：">{{orderInfo.createTime}}</el-form-item>
                      </el-col>

                      <el-col :span="8">
                          <el-form-item label="供方开票日期：" label-width="220px">{{orderInfo.invoice}}<span v-if="orderInfo.invoice != ''">号前</span></el-form-item>
                      </el-col>
                  </el-row>
                  <el-row>
                      <el-col :span="8">
                          <el-form-item label="合同公司：">{{orderInfo.fromCompany}}</el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="供应商：">{{orderInfo.supplierName}}</el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="结算方式、时间及地点：" label-width="220px">{{orderInfo.remark}}</el-form-item>
                      </el-col>

                  </el-row>
                  <el-row>
                      <el-col :span="8">
                          <el-form-item label="交货方式：">{{orderInfo.deliveryType}}</el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="交货地点：">{{orderInfo.deliveryCity}}</el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="运输方式及到达（港）和费用负担：" label-width="220px">
                              {{orderInfo.freightType}}
                          </el-form-item>
                      </el-col>
                  </el-row>

                  <el-row>
                      <el-col :span="8">
                          <el-form-item label="业务员：">
                              {{orderInfo.userName}}
                          </el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="合同附加条款：">
                              {{orderInfo.otherRemark}}
                          </el-form-item>
                      </el-col>
                      <el-col :span="8">
                          <el-form-item label="交（提）货方式、地点：" label-width="220px">{{orderInfo.sendType}}</el-form-item>
                      </el-col>
                  </el-row>
                  <el-row>
                      <el-col :span="8">
                          <el-form-item label="采购员：">
                              {{orderInfo.buyerUserName}}
                              <el-button type="text" style="margin-left:5px" @click="showDialogEdit">修改</el-button>
                          </el-form-item>
                      </el-col>
                      <el-col :span="8" v-if="orderInfo && orderInfo.orderState === 0">
                        <el-form-item label="合同性质：" prop="contractNature"  key="contractNature1">
                            <el-select v-model="orderInfo.contractNature" size="small" clearable>
                              <el-option value="公司政策" label="公司政策" key="1"></el-option>
                              <el-option value="采购囤货" label="采购囤货" key="2"></el-option>
                              <el-option value="对锁订单" label="对锁订单" key="3"></el-option>
                              <el-option value="采购预售" label="采购预售" key="4"></el-option>
                            </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8" v-else>
                        <el-form-item label="合同性质：" key="contractNature2">
                          {{orderInfo.contractNature}}
                        </el-form-item>
                      </el-col>
                    </el-row>
            </el-card>
            <div style="margin-top: 20px">
              <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
              <span class="font-small">商品信息</span>
            </div>
            <el-table
                   ref="orderItemTable"
                   :data="orderInfo.ordGoodsList"
                   style="width: 100%;margin-top: 20px" border>
                     <el-table-column label="商品名称" width="160" align="center">
                       <template slot-scope="scope">
                         {{scope.row.goodsName}}
                       </template>
                     </el-table-column>
                    <el-table-column label="商品牌号" align="center" width="160">
                        <template slot-scope="scope">
                            {{scope.row.goodsSn}}
                        </template>
                    </el-table-column>
                    <el-table-column label="采购单价" width="150" align="center">
                        <template slot-scope="scope">
                            {{scope.row.goodsPrice}}
                        </template>
                    </el-table-column>
                     <el-table-column label="采购数量"   width="100"  align="center">
                       <template slot-scope="scope">
                           {{scope.row.goodsNum}}
                       </template>
                     </el-table-column>
                    <el-table-column label="采购单位"   width="80"  align="center">
                        <template slot-scope="scope">
                          {{scope.row.goodsUnit}}
                        </template>
                    </el-table-column>
                     <el-table-column label="采购金额"   width="100" align="center">
                       <template slot-scope="scope">
                           ￥{{scope.row.goodsAmount}}
                       </template>
                     </el-table-column>
                    <el-table-column label="每吨销售采购毛利"   width="150" align="center">
                        <template slot-scope="scope">
                            ￥{{scope.row.perProfit}}
                        </template>
                    </el-table-column>
                    <el-table-column label="杂费(装卸费)"   width="100" align="center">
                        <template slot-scope="scope">
                            <el-input v-if="orderInfo.orderState == 0" v-model="scope.row.goodsConsultation" size="small"></el-input>
                            <div v-else>
                                {{scope.row.goodsConsultation}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="结算方式"   width="100" align="center">
                      <template slot-scope="scope">
                          {{scope.row.goodsSettleType}}
                      </template>
                    </el-table-column>
                    <el-table-column label="备注" align="center" width="200">
                        <template slot-scope="scope">
                            <div>{{scope.row.goodsRemark }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="底色" align="center" width="200">
                        <template slot-scope="scope">
                            <div v-if="orderInfo.orderState == 0">
                                <el-select v-model="scope.row.goodsColor" size="small" :disabled="scope.row.isNeedInputColor == 0" clearable>
                                    <el-option value="蓝底透明" label="蓝底透明" key="1"></el-option>
                                    <el-option value="白底透明" label="白底透明" key="2"></el-option>
                                    <el-option value="黑底透明" label="黑底透明" key="3"></el-option>
                                  <el-option value="颜色备注" label="颜色备注" key="4"></el-option>
                                </el-select>
                            </div>
                            <div v-else>{{scope.row.goodsColor }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="交货日期" width="100" align="center">
                        <template slot-scope="scope">
                            <div>{{scope.row.goodsDeliveryDate }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="预计发货地" width="200" align="center">
                        <template slot-scope="scope">
                            <div>{{scope.row.goodsDeliveryCity }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="业务性质" width="120" align="center">
                      <template slot-scope="scope">
                        <div>{{scope.row.businessType }}</div>
                      </template>
                    </el-table-column>

                    <el-table-column label="适配销售订单" align="center" width="460"  fixed="right">
                      <template slot-scope="scope">
                        <div v-if="orderInfo.orderState == 0 && scope.row.crmOrderList.length == 0">
                          <el-form-item :prop="`ordGoodsList.${scope.$index}.crmOrderIds`" :rules="rules.crmOrderIds" label-width="0">
                            <el-select
                              class="zdy-sec"
                              popper-class="zdy-op"
                              style="width:420px"
                              multiple
                              clearable
                              v-model="scope.row.crmOrderIds"
                              @visible-change="showSel('',scope.row,scope.$index,$event)"
                              :loading="crmOrderLoading">
                              <el-option
                                v-for="(item,index) in scope.row.orderList"
                                :key="index"
                                :label="'合同编号:'+item.orderSn+',数量:'+item.goodsNum+',发货方式:'+item.sendType+'\n采购报价:'+item.purchasePrice+',采购底价:'+item.purchaseActualPrice"
                                :value="item.orderId">
                              </el-option>
                            </el-select>
                          </el-form-item>
                        </div>
                        <div v-else>
                           <span v-for="(item,index) in scope.row.crmOrderList" :key="index">
                              <span style="color:#409eff;cursor:pointer;" @click="toOrderDetail(item.orderId)">{{item.orderSn}}</span>
                              <span v-if="index < scope.row.crmOrderList.length-1">,</span>
                           </span>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="是否开票结算" width="100" align="center"  fixed="right">
                      <template slot-scope="scope">
                          {{scope.row.isOrderSettle == 1 ? '是' : '否'}}
                      </template>
                    </el-table-column>

            </el-table>
            <div style="text-align: right;margin-top:20px;font-size:12px;">订单数量：{{orderInfo.goodsAllNum}}<span style="padding-left:20px">订单金额：{{orderInfo.orderAmount}}</span></div>
       </el-form>
         <div style="margin-top: 20px;clear: both">
             <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
             <span class="font-small">入库单信息</span>
         </div>

    <el-table
            ref="orderItemTable"
            :data="orderInfo.entryGoodsList"
            style="width: 100%;margin-top: 20px" border>
        <el-table-column label="单据类型"  width="100" align="center">
            <template slot-scope="scope">
                {{scope.row.entryType}}
            </template>
        </el-table-column>
        <el-table-column label="入库单号" width="160" align="center">
            <template slot-scope="scope">
                <el-link type="primary" @click="toentryinfo(scope.row)" style="vertical-align: middle;">
                    {{scope.row.entrySn}}
                </el-link>
                <img src="../../assets/images/zhuofei2.png" v-if="scope.row.isDelete == 1" style="vertical-align: middle;"/>

            </template>
        </el-table-column>
        <el-table-column label="入库日期"   width="100"  align="center">
            <template slot-scope="scope">
                {{scope.row.createTime}}
            </template>
        </el-table-column>
        <el-table-column label="商品名称"   width="150" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsName}}
            </template>
        </el-table-column>
        <el-table-column label="商品牌号" width="150" align="center">
            <template slot-scope="scope">
                <div>{{scope.row.goodsSn }}</div>
            </template>
        </el-table-column>
        <el-table-column label="入库批号" width="150" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsBatchNo }}
            </template>
        </el-table-column>

        <el-table-column label="入库数量" width="100" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsNum }}
            </template>
        </el-table-column>
        <el-table-column label="单位" width="80" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsUnit }}
            </template>
        </el-table-column>
        <el-table-column label="单价" width="100" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsPrice}}
            </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="结算方式"
          width="100">
          <template slot-scope="scope">
            {{scope.row.goodsPayMethod}}
          </template>
        </el-table-column>
        <el-table-column label="总额" width="100" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsAmount}}
            </template>
        </el-table-column>
        <el-table-column label="仓库" width="100" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsWarehouse}}
            </template>
        </el-table-column>
        <el-table-column label="备注" width="150" align="center">
            <template slot-scope="scope">
                {{scope.row.goodsRemark}}
            </template>
        </el-table-column>
    </el-table>
    <div style="margin-top:20px">
        <el-form :rules="rules" :model="orderInfo" ref="orderInfo" size="small" inline>
            <!--采购确认时必填，其它状态显示-->
<!--            <el-form-item label="付款条款：" prop="payOtherRemark" v-if="orderInfo.orderState == 0">-->
<!--                <el-input type="textarea" style="width:300px" v-model.trim="orderInfo.payOtherRemark"></el-input>-->
<!--            </el-form-item>-->
<!--            <div v-if="orderInfo.orderState != 0" style="font-size:12px;margin-bottom:20px">-->
<!--                付款条款:{{orderInfo.payOtherRemark}}-->
<!--            </div>-->
            <!--回退时必填，-->
            <el-form-item label="审核备注（回退时必填）："  v-if="orderInfo.orderState == 20 || orderInfo.orderState == 23 ||orderInfo.orderState == 25 ||orderInfo.orderState == 30">
                <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" style="width:300px" v-model.trim="remark"></el-input>
            </el-form-item>

            <!--采购员审核必填，-->
            <el-form-item label="合同类型："  v-if="orderInfo.orderState == 0 &&  orderInfo.userId == userId">
                <el-radio-group v-model="orderInfo.contractType">
                    <el-radio label="self">公司合同</el-radio>
                    <el-radio label="other">外部合同</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </div>

        <div style="text-align: center;clear: both;margin-top:20px">

            <!--采购确认时,只能审核自已负责的合同-->
            <span v-if="orderInfo.orderState == 0">
                <el-button type="primary" @click="handleConfirm" :loading="btnLoading" v-if="orderInfo.userId == userId">采购审核</el-button>
                <el-button type="primary"  @click="toPrint(2)" v-if="orderInfo.contractType == 'self'">合同预览</el-button>
            </span>

            <!--采购负责人确认或产品负责人确认时，并且为负责人才有采购审核-->
            <span v-if="orderInfo.orderState == 20 || orderInfo.orderState == 23">
                <el-button type="primary" @click="handleConfirm" :loading="btnLoading" v-if="orderInfo.isNeedMyCheck == 1">采购审核</el-button>
                <el-button type="primary"  @click="toPrint(2)" v-if="orderInfo.contractType == 'self'">合同预览</el-button>
                <el-button @click="blackOrder" :loading="btnLoading1" v-if="orderInfo.isNeedMyCheck == 1">回 退</el-button>
            </span>

            <!--老板审核-->
            <span v-if="orderInfo.orderState == 25">
                <el-button type="primary" @click="handleConfirm" :loading="btnLoading" v-if="orderInfo.isNeedMyCheck == 1">总经理审核</el-button>
                <el-button type="primary"  @click="toPrint(2)" v-if="orderInfo.contractType == 'self'">合同预览</el-button>
                <el-button @click="blackOrder" :loading="btnLoading1" v-if="orderInfo.isNeedMyCheck == 1">回 退</el-button>
            </span>

            <!--待付款，待财务审核，交易成功-->
            <span v-if="orderInfo.orderState > 25 && orderInfo.orderState < 50">
                <el-button type="primary"  @click="toPrint(1)" v-if="orderInfo.contractType == 'self'">合同打印</el-button>
            </span>
            <el-button type="primary" @click="showDialogRemark">添加备注</el-button>
            <el-button  @click="showDialogCancel" v-if="orderInfo.isCanCancel">取消</el-button>

        </div>

         <div style="margin-top: 20px;clear: both">
             <el-menu :default-active="logTab" class="el-menu-demo" mode="horizontal" @select="handleSelectLog">
                 <el-menu-item index="1">操作记录</el-menu-item>
                 <el-menu-item index="2">变更记录</el-menu-item>
                 <el-menu-item index="3">订单备注</el-menu-item>
                 <el-menu-item index="4">合同上传</el-menu-item>
                 <el-menu-item index="5">付款记录</el-menu-item>

             </el-menu>
         </div>

         <div style="margin-top:20px;border:1px solid #EBEEF5;padding:20px 20px 0 20px">
             <div v-if="logTab == 1 || logTab == 2 || logTab == 3">
                 <el-timeline>
                     <el-timeline-item
                             v-for="(activity, index) in orderLogs"
                             :key="index">
                         <span>
                             <span style="padding-right:10px;">{{activity.created_at}}</span>
                             {{activity.user_name}}：{{activity.content}}
                             <span v-show="activity.remark && activity.remark != ''" style="color:red;padding-left:5px">备注：{{activity.remark}}</span>
                             <!--                              <span v-show="logTab == 1" style="padding-left:5px">耗时：{{activity.time_consuming}}</span>-->
                         </span>
                     </el-timeline-item>
                 </el-timeline>
                 <div style="color:#888;padding:20px;text-align: center;font-size:12px" v-if="orderLogs.length == 0">- 暂无数据 -</div>
             </div>
             <div v-else-if="logTab == 4" style="padding-bottom:20px;">
                 <el-upload action="https://upload.qiniup.com"
                            drag
                            style="width:500px"
                            :http-request="sliderRequest"
                            :limit="10"
                            :on-exceed="onExceed"
                            list-type="picture"
                            :file-list="fileList"
                            :before-remove="beforeRemove"
                            :on-remove="onRemove"
                            :on-preview="preview">
                             <i class="el-icon-upload"></i>
                             <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
<!--                     <el-button size="small" type="primary" :disabled="fileList.length>=5">点击上传</el-button>-->
                 </el-upload>
                 <div style="font-size:12px;color:#888;padding-top:10px" v-if="fileList.length > 0 && orderInfo.contractFiles">这是一个{{orderInfo.contractFiles.extension}}文件，如下载后无法打开请加上.{{orderInfo.contractFiles.extension}}</div>
             </div>
             <div v-else-if="logTab == 5" style="padding-bottom:20px;">
                 <el-table
                         ref="orderItemTable"
                         :data="orderInfo.orderPayList"
                         style="width: 100%;margin-top: 20px" border>
                     <el-table-column label="付款日期" align="center">
                         <template slot-scope="scope">
                             {{scope.row.payTime}}
                         </template>
                     </el-table-column>
                     <el-table-column label="付款方式" align="center">
                         <template slot-scope="scope">
                             {{scope.row.payType}}
                         </template>
                     </el-table-column>
                     <el-table-column label="付款人" align="center">
                         <template slot-scope="scope">
                             {{scope.row.operator}}
                         </template>
                     </el-table-column>
                     <el-table-column label="付款金额" align="center">
                         <template slot-scope="scope">
                             {{scope.row.payAmount}}
                         </template>
                     </el-table-column>
                     <el-table-column label="付款凭证" align="center">
                         <template slot-scope="scope">
                             <img :src="item" v-for="item in scope.row.payContent" @click="fullImg(item)" style="width:50px;height:50px;object-fit: contain;margin-right:5px"/>
                         </template>
                     </el-table-column>
<!--                     <el-table-column label="付款状态" align="center">-->
<!--                         <template slot-scope="scope">-->
<!--                             {{scope.row.payState | fiferPayState}}-->
<!--                         </template>-->
<!--                     </el-table-column>-->
                     <el-table-column label="付款备注" align="center">
                         <template slot-scope="scope">
                             {{scope.row.remark}}
                         </template>
                     </el-table-column>

                 </el-table>
             </div>
         </div>
    </el-card>

      <!--备注-->
      <el-dialog
              :close-on-click-modal="false"
              :beforeClose="handleClose3"
              title="填写备注"
              :visible.sync="dialogVisible3"
              width="400px">
          <el-form :model="remarkForm" size="mini" label-width="100px"  ref="remarkForm" :rules="rules3">
              <el-form-item label="备注类型：" prop="remarkTypeStr">
                  <el-select v-model.number="remarkForm.remarkTypeStr" class="input-width" style="width:195px" placeholder="请选择">
                      <el-option :value="item.cddValue" :label="item.cddValue" :key="item.cddValue" v-for="item in remarkList"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="调整原因：" prop="remark">
                  <el-input v-model="remarkForm.remark" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
              </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
              <el-button @click="handleClose3">取 消</el-button>
              <el-button type="primary" @click="handleConfirm3" :loading="btnLoading3">确 定</el-button>
          </span>
      </el-dialog>


      <!--修改采购员弹窗-->
      <el-dialog
              :close-on-click-modal="false"
              :beforeClose="handleClose5"
              title="修改采购员"
              :visible.sync="dialogVisible5"
              width="660px">
          <el-form :model="editForm" size="mini" label-width="100px"  ref="editForm" :rules="rules5">
              <el-form-item label="采购员：" prop="buyerUserId">
                  <el-select v-model="editForm.buyerUserId" filterable placeholder="请选择">
                      <el-option
                              v-for="item in userOptionList"
                              :key="item.userId"
                              :label="item.userName"
                              :value="item.userId">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-table
                      ref="orderItemTable"
                      :data="editForm.ordGoodsList"
                      style="width: 100%;margin-top: 20px" border>
                  <el-table-column label="商品名称" width="160" align="center">
                      <template slot-scope="scope">
                          {{scope.row.goodsName}}
                      </template>
                  </el-table-column>
                  <el-table-column label="商品牌号" align="center" width="160">
                      <template slot-scope="scope">
                          {{scope.row.goodsSn}}
                      </template>
                  </el-table-column>
                  <el-table-column label="采购单价" width="150" align="center">
                      <template slot-scope="scope">
                          {{scope.row.goodsPrice}}
                      </template>
                  </el-table-column>
                  <el-table-column label="每吨销售采购毛利" width="150" align="center">
                      <template slot-scope="scope">
                          <el-form-item label-width="0" :prop="`ordGoodsList.${scope.$index}.perProfit`" :rules="rules5.perProfit">
                              <el-input v-model="scope.row.perProfit"></el-input>
                          </el-form-item>
                      </template>
                  </el-table-column>
              </el-table>
          </el-form>
          <span slot="footer" class="dialog-footer">
              <el-button @click="handleClose5">取 消</el-button>
              <el-button type="primary" @click="handleConfirm5" :loading="btnLoading6">确 定</el-button>
          </span>
      </el-dialog>
      <!--放大图片-->
      <el-dialog
              :visible.sync="dialogVisible4"
              width="800px">
          <img :src="fullSrc" style="width:100%;"/>
      </el-dialog>

    <!--取消-->
    <el-dialog
      title="合同取消"
      :visible.sync="dialogVisible7"
      width="400px">
      <el-form :model="cancelForm" size="mini" label-width="100px"  ref="cancelForm">
        <el-form-item label="取消原因：">
          <el-input v-model="cancelForm.remark" :autosize="{ minRows: 2, maxRows: 6}" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
              <el-button @click="handleClose7">取 消</el-button>
              <el-button type="primary" @click="handleConfirm7" :loading="btnLoading7">确 定</el-button>
          </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import axios from 'axios';
import store from '@/store';
import {
  getQiniuToken,
  purchaseProcess,
  purchaseOrderDetail,
  purchaseUploadFiles,
  getCustomerSetting,
  purchaseRemark,
  syncOneKingOrderPurchase,
  getOrderUsersList,
  changeBuyerUserId
} from '@/api/partner';
import { getCrmOrderList } from '@/api/order';
import { validateCommission } from '@/utils/validate';
import {purchaseOrderCancel} from '@/api/company'
const defaultCancelForm={
    orderId: '',
    remark: '',

  }
export default {
  name: "customerDetail",
  data() {
    const isvalidateCrmOrderIds = (rule, value, callback) => {
      if (value.length == 0 && (this.orderInfo.contractNature == '对锁订单' || this.orderInfo.contractNature == '采购预售')) {
        callback(new Error('请选择适配销售订单'))
      } else {
        callback()
      }
    };
    return {
      roles: store.getters.roles ? store.getters.roles : [],
      loading: false,
      orderId: this.$route.query.id,
      orderInfo: {},
      btnLoading: false,
      pumsRemark: '',
      btnLoading1: false,
      logTab: '1',
      orderLogs: [],
      deliverForm: {},
      fileList: [],
      uploadToken: {
        token: '',
      },
      imgDomain: '',
      remark: '',
      rules: {
        contractNature: [{ required: true, trigger: ['blur', 'change'], message: '请选择合同性质' }],
        crmOrderIds: [{ required: true, trigger: 'change', validator: isvalidateCrmOrderIds, }],
      },
      dialogVisible3: false,
      btnLoading3: false,
      remarkForm: {
        remarkTypeStr: '',
        remark: '',
      },
      rules3: {
        remarkTypeStr: [{ required: true, trigger: 'change', message: '请选择备注类型', }],
        remark: [{ required: true, trigger: 'blur', message: '请输入备注', }],
      },
      remarkList: [],
      fullSrc: '',
      dialogVisible4: false,
      btnLoading5: false,
      contractType: '',

      dialogVisible5: false,
      btnLoading6: false,
      editForm: {
        buyerUserId: '',
        ordGoodsList: [],

      },
      rules5: {
        buyerUserId: [{ required: true, trigger: 'chane', message: '请选择采购员', }],
        perProfit: [{ required: true, trigger: 'blur', message: '此项必填', }]
      },
      userOptionList: [],
      crmOrderLoading: false,

      dialogVisible7: false,
      btnLoading7: false,
      cancelForm: JSON.parse(JSON.stringify(defaultCancelForm))

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId',
      'isMange',
    ]),
  },
  created() {
    this.getPageInfo();
    this.getUploadToken();
    this.getRemarkList();
    this.getUserOptionList();
  },

  filters: {
    fiferPayState(val) {
      if (val == 0) {
        return '未付款'
      } else if (val == 1) {
        return '部分付款'
      } else if (val == 2) {
        return '已付款'
      }
    },
  },
  methods: {
    //取消
    showDialogCancel(){
        this.cancelForm = JSON.parse(JSON.stringify(defaultCancelForm))
        this.dialogVisible7 = true;

    },
    handleClose7(){
      this.dialogVisible7 = false
    },
    handleConfirm7(){
      this.$refs['cancelForm'].validate((valid) => {
        if (valid) {
          this.btnLoading7 = true;
          this.cancelForm.orderId = this.orderId
          purchaseOrderCancel(this.cancelForm ).then(() => {
            this.btnLoading7 = false;
            this.dialogVisible7 = false;
            this.getPageInfo()
          }).catch(() => {
            this.btnLoading7 = false;
          })
        }
      })
    },
    toOrderDetail(orderId) {
      let routeData = this.$router.resolve({ name: 'purchaseDetail', query: { id: orderId, type: 'see' } });
      window.open(routeData.href);
    },
    showSel(query, item, index, e) {
      if (e) {
        this.remoteMethod(query, item, index)
      }
    },
    remoteMethod(query, item, index) {
      this.crmOrderLoading = true
      console.log(index)
      getCrmOrderList({ sapGoodsId: item.sapGoodsId, orderSn: query }).then((res) => {
        let c = JSON.parse(JSON.stringify(this.orderInfo.ordGoodsList[index]))
        c.orderList = res
        console.log(c)
        this.orderInfo.ordGoodsList.splice(index, 1, c)
        this.crmOrderLoading = false
        console.log(this.orderInfo.ordGoodsList)
      }).catch(() => {
        this.crmOrderLoading = false
      })
    },
    //显示修改采购员弹窗
    showDialogEdit() {
      this.dialogVisible5 = true;
      this.editForm.buyerUserId = this.orderInfo.buyerUserId;
      this.editForm.ordGoodsList = JSON.parse(JSON.stringify(this.orderInfo.ordGoodsList));
      // this.editForm.ordGoodsList.forEach((el,index)=>{
      //     let c = JSON.parse(JSON.stringify(el));
      //     c.perProfit = '';
      //     this.$set(this.editForm.ordGoodsList,index,c)
      // })
    },
    //关闭修改采购员
    handleClose5() {
      this.dialogVisible5 = false;
      this.$refs.editForm.clearValidate();
    },
    //提交修改采购员
    handleConfirm5() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.btnLoading6 = true;
          let data = {};
          data.orderId = this.orderId;
          data.buyerUserId = this.editForm.buyerUserId;
          data.ordGoodsList = [];
          this.editForm.ordGoodsList.forEach((el) => {
            data.ordGoodsList.push({ pogId: el.pogId, perProfit: el.perProfit })
          })
          changeBuyerUserId(data).then(() => {
            this.btnLoading6 = false;
            this.dialogVisible5 = false;
            this.getPageInfo()
          }).catch(() => {
            this.btnLoading6 = false;
          })
        }
      })
    },


    //获取员工下拉选项
    getUserOptionList() {
      getOrderUsersList().then((res) => {
        this.userOptionList = res;
      })
    },

    toentryinfo(item) {
      let routeData = this.$router.resolve({ name: 'inWarehouseDetail', query: { id: item.entryId } });
      window.open(routeData.href);
    },
    //同步SAP数据
    syncOneOrder() {
      this.btnLoading5 = true;
      syncOneKingOrderPurchase({ orderId: this.orderId }).then((res) => {
        this.$message({
          message: '同步成功',
          type: 'success'
        });
        this.btnLoading5 = false;
        this.getPageInfo()
      }).catch(() => {
        this.btnLoading5 = false;
      })
    },
    fullImg(src) {
      this.dialogVisible4 = true;
      this.fullSrc = src;
    },
    //切换log类型
    handleSelectLog(key) {
      this.logTab = key;
      this.orderLogs = [];
      if (key == 1) {
        this.orderLogs = this.orderInfo.ordLogList.orderLogByA
      } else if (key == 2) {
        this.orderLogs = this.orderInfo.ordLogList.orderLogByB
      } else {
        this.orderLogs = this.orderInfo.ordLogList.orderLogByC
      }
    },
    //获取备注类型
    getRemarkList() {
      getCustomerSetting().then((res) => {
        res.forEach((el) => {
          if (el.cdtCode == 'remark_type_str') {
            this.remarkList = el.data
          }
        });
      })
    },
    //显示备注弹窗
    showDialogRemark() {
      this.dialogVisible3 = true;
      this.remarkForm.remark = '';
    },
    //关闭备注弹窗
    handleClose3() {
      this.dialogVisible3 = false;
      this.$refs.remarkForm.clearValidate();
    },
    //提交备注
    handleConfirm3() {
      this.$refs['remarkForm'].validate((valid) => {
        if (valid) {
          this.btnLoading3 = true;
          purchaseRemark({ orderId: this.orderId, remark: this.remarkForm.remark, remarkTypeStr: this.remarkForm.remarkTypeStr }).then(() => {
            this.btnLoading3 = false;
            this.dialogVisible3 = false;
            this.getPageInfo()
          }).catch(() => {
            this.btnLoading3 = false;
          })
        }
      })
    },
    //获取七牛TOKEN
    getUploadToken() {
      getQiniuToken().then((res) => {
        this.uploadToken.token = res.token;
        this.imgDomain = res.domain
      })
    },
    //上传文件重写
    sliderRequest(upload) {
      // 文件上传自行处理上传
      // 创建FormData对象 添加相关上传参数
      const formData = new FormData()
      // 文件对象
      formData.append('file', upload.file)
      // key 文件名处理，这样的话七牛会识别文件时什么类型
      let timestamp = new Date().getTime();
      let fileName = timestamp + upload.file.name
      formData.append('key', fileName)
      // token
      formData.append('token', this.uploadToken.token)//这个postData,要在data数据里面进行定义的，，，我这里调接口使用的是vue的方式
      // 上传文件
      // onUploadProgress 查看axios文档 https://github.com/axios/axios
      axios.post("https://upload.qiniup.com", formData, {
        onUploadProgress: (event) => {
          // 监听上传进度
          event.percent = event.loaded / event.total * 100
          upload.onProgress(event)
        }
      }).then((response) => {
        console.log("response", response)
        if (response.status === 200) {
          let res = response.data;
          console.log(this.imgDomain + res.key);
          let newFile = this.imgDomain + res.key;
          this.fileList.push({ name: newFile, url: newFile });
          console.log("this.fileList", this.fileList)
          this.uploadfileList('upload');

        } else {
          this.handleAvatarError()
        }
      }).catch((err) => {
        // 调用组件上传失败方法
        this.handleAvatarError()
      })
    },

    uploadfileList(type) {
      let contractUrl = '';
      if (this.fileList.length > 0) {
        let list = [];
        this.fileList.forEach((el) => {
          list.push(el.url)
        })
        contractUrl = list.join(",")
      }
      purchaseUploadFiles({ orderId: this.orderId, contractUrl: contractUrl }).then((res) => {
        this.getPageInfo();
        let msg = type == 'del' ? '附件已删除' : '合同附件上传成功';
        this.$message({
          message: msg,
          type: 'success'
        });
      }).catch(() => {
      })
    },

    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    preview(file) {
      window.open(file.name)
    },

    beforeRemove(file, fileList) {
      return this.$confirm('确定删除图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(fileList);
      }).catch(() => {
        reject(false);
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    onRemove(file, fileList) {
      this.fileList = fileList
      this.uploadfileList('del');
    },
    onExceed(file, fileList) {
      this.$message({
        message: '最多上传10个附件',
        type: 'error'
      });
    },


    //去打印机
    toPrint(type) {
      this.$router.push({ name: 'purchasePrinting', query: { id: this.$route.query.id, type: type, } })
    },


    //返回
    goBlack() {
      this.$router.go(-1)
    },

    //确认提交
    handleConfirm() {
      this.$refs['orderForm'].validate((valid) => {
        console.log(valid)
        if (valid) {
          let data = {};
          data.orderId = this.orderId;
          if (this.orderInfo.orderState == 0) {
            data.action = 'purchaseCheck';
            data.contractType = this.orderInfo.contractType;
            data.contractNature = this.orderInfo.contractNature
          } else if (this.orderInfo.orderState == 20) {
            data.action = 'purchaseReCheck'
          } else if (this.orderInfo.orderState == 23) {
            data.action = 'pPurchaseReCheck'
          } else if (this.orderInfo.orderState == 25) {
            data.action = 'bossCheck'
          }
          if (this.orderInfo.orderState == 0 && this.orderInfo.contractType == '') {
            this.$message.error('请选择合同类型！');
            return false
          }
          if (this.orderInfo.orderState == 0) {
            data.ordGoodsList = [];
            let noColor = 0;
            this.orderInfo.ordGoodsList.forEach((el) => {
              if (el.isNeedInputColor == 1) {
                if (el.goodsColor == '') {
                  noColor = 1
                }
                data.ordGoodsList.push({ pogId: el.pogId, goodsColor: el.goodsColor, goodsConsultation: el.goodsConsultation, crmOrderIds: el.crmOrderIds });
              } else {
                data.ordGoodsList.push({ pogId: el.pogId, goodsColor: '', goodsConsultation: el.goodsConsultation, crmOrderIds: el.crmOrderIds });
              }
            });
            if (noColor == 1) {
              this.$message({
                message: '请选择底色',
                type: 'error',
                duration: 1000
              });
              return false
            }
          }
          this.btnLoading = true;
          data.payOtherRemark = this.orderInfo.orderState == 0 ? this.orderInfo.payOtherRemark : '';
          purchaseProcess(data).then(() => {
            this.btnLoading = false;
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            // this.$router.go(-1);
            this.getPageInfo();
          }).catch(() => {
            this.btnLoading = false;
          })
        }
      })
    },

    //回退
    blackOrder() {
      if (this.remark == '') {
        this.$message.error('回退时，审核备注必需填写！');
        return false
      }
      this.btnLoading1 = true;
      let data = {};
      data.orderId = this.orderId;
      data.action = 'back';
      data.remark = this.remark;
      purchaseProcess(data).then(() => {
        this.btnLoading1 = false;
        this.$message({
          message: '合同已回退成功',
          type: 'success'
        });
        // this.$router.go(-1);
        this.getPageInfo();
      }).catch(() => {
        this.btnLoading1 = false;
      })
    },

    //获取合同详情
    getPageInfo() {
      this.loading = true;
      purchaseOrderDetail({ orderId: this.orderId }).then(res => {
        let data = res;
        data.ordGoodsList.forEach((el) => {
          el.crmOrderIds = [];
          el.orderList = [];
          if(data.orderState == 0){
            el.crmOrderList.forEach((ee)=>{
              el.crmOrderIds.push(ee.orderId)
            })
          }
        })
        this.orderInfo = data;
        this.fileList = [];
        if (this.orderInfo.contractUrl != '') {
          let contractUrl = this.orderInfo.contractUrl.split(",");
          contractUrl.forEach((el) => {
            this.fileList.push({ name: el, url: el })
          })
        }
        this.handleSelectLog(this.logTab);
        this.loading = false;
      });
    },
  },
  watch: {
    '$route'(to, from) {
      this.orderId = this.$route.query.id;
      this.getPageInfo();
    }
  },
};
</script>
<style>
.zdy-sec .el-select__tags-text{
  width:150px;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  vertical-align: middle;
}
.zdy-op .el-select-dropdown__item{
  height:auto;
  min-height: 34px;
  font-size: 14px;
  padding: 0 20px;
  position: relative;
  white-space: pre-line;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  line-height: 16px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  cursor: pointer;
  margin-bottom: 10px;
}
</style>
<style lang="scss" scoped>

  .detail-container {
    width: 90%;
    padding: 20px 20px 20px 20px;
    margin: 20px auto;
    .el-card__header{
      background: #f8f8f8;
      .kehu-name{
        display: inline-block;
        font-size:14px;
        vertical-align: middle;
      }
      .kehu-label{
        font-size:12px;
        vertical-align: middle;
        display: inline-block;
        margin-left:15px;
        color: #409eff;
        background: #ecf5ff;
        border: 1px solid #b3d8ff;
        height:24px;
        line-height: 24px;
        padding:0 10px;
        border-radius: 5px;
      }
      .kehu-info{
        text-align: right;
        font-size: 12px;
        color:#333;
        line-height: 20px;
        span{
          padding-left:16px;
        }
      }
    }
    .operate-container {
      background: #F2F6FC;
      height: 80px;
      margin: -20px -20px 0;
      line-height: 80px;
    }
  }
  .price-block{
    font-size:12px;
    line-height:30px;
    .lab{
      display: inline-block;
      width:100px;
      text-align: right;
    }
    .text{
      display: inline-block;
    }
  }
  .minRoW .el-form-item{
      margin-bottom:5px;
  }
  .tongJitable{
      border-left:1px solid #EBEEF5;
      border-top:1px solid #EBEEF5;
      font-size:12px;
      margin-bottom:20px;
      td{
          border-right:1px solid #EBEEF5;
          border-bottom:1px solid #EBEEF5;
          div.tddiv{
              min-height: 30px;
              line-height: 30px;
              padding:0 5px;
              text-align: center;
              white-space:  nowrap
          }
      }
      .bgtd{
          background: #f5f7fa;
      }
  }
</style>
